package pers.cz.mock;

import com.alibaba.fastjson.JSON;
import pers.cz.config.MybatisSqlSessionFactory;
import pers.cz.context.MyThreadLocals;
import pers.cz.entity.AutoCollectMethodParamsMapper;
import pers.cz.transform.ParamsAndReurnEasyFrameTransformer;
import pers.cz.util.*;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.sql.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: postgirl-collection-client
 * @description: ParamsAndReturnMock
 * @author: Cheng Zhi
 * @create: 2022-03-02 09:31
 **/
public class ParamsAndReturnMock {

    private static RedisConfig redisUtil = null;

    static {
        redisUtil = new RedisConfig();
    }

    public static Object begin(Class clazz, Object object) {
        try {
            System.out.println("------------监听到了入参------start---" + JSON.toJSONString(object));

            if (MyThreadLocals.methodContext.get() != null) {
                System.out.println("------cz------test-----从库里获取---");
                // 查数据库比对
                int requestHashCode = JSON.toJSONString(object).hashCode();
                System.out.println("-------该请求的hashcode为：" + requestHashCode);
                String myResponse = getResult(null, String.valueOf(requestHashCode));
                if (myResponse != null) {
                    System.out.println("------cz------test----获取到了---" + myResponse);
                    return JsonUtil.jsonToList(myResponse, clazz);
                } else {
                    System.out.println("查询了但是没有查询到");
                }
            }
            System.out.println("------------监听到了入参-------end----");
        } catch (Exception e) {
            System.out.println("-------------start出错了-------------" + e.getMessage());
        }
        return null;
    }

    public static void end(Object targetMehod, Object request, Object response, String methodName) {

        try {
            // 只有是接口请求才录制,并且不是postgirl发起的请求才录制
            if (MyThreadLocals.context.get() != null && MyThreadLocals.methodContext.get() == null) {

                // 查询
                if (ParamsAndReurnEasyFrameTransformer.SELECT.equals(methodName)) {

                }
                System.out.println("-------------监听到了出参------start-----");
                ColletExecutor executor = ColletExecutor.getInstance(CollectType.INTERFACE_COLLECT);
                JedisPool jedisPool = redisUtil.redisPoolFactory();
                Jedis resource = jedisPool.getResource();
                System.out.println("-------------提交线程-----");
                System.out.println("目标方法名：" + JSON.toJSONString(methodName));
                System.out.println("请求：" + JSON.toJSONString(request));
                System.out.println("响应：" + JSON.toJSONString(response));
                String traceId = MyThreadLocals.context.get();
                executor.executeTask(new ParamsAndReturnThread(JSON.toJSONString(targetMehod),JSON.toJSONString(request), JSON.toJSONString(response), methodName, resource, traceId));
                System.out.println("-------------监听到了出参------ end -----");
                // 插入

            }

        } catch (Exception e) {
            System.out.println("------end出错了...." + e.getMessage());
        }
    }

    /**
     * 查询数据库获取响应
     * @param targetMethod      目标方法
     * @param requestHashCode   请求的hashcode值
     * @return
     */
    private static String getResult(String targetMethod, String requestHashCode) {

        MybatisSqlSessionFactory mybatisSqlSessionFactory = MybatisSqlSessionFactory.getMybatisSqlSessionFactory();
        SqlSessionFactory sqlSessionFactory = mybatisSqlSessionFactory.getSqlSessionFactory();
        SqlSession sqlSession = sqlSessionFactory.openSession();
        List<String> list = sqlSession.getMapper(AutoCollectMethodParamsMapper.class).selectByRequestHashCode(requestHashCode);
        if (list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    /**
     * 查询数据库获取响应
     * @param targetMethod      目标方法
     * @param request           请求的hashcode值
     * @return
     */
    private static String getResult1(String targetMethod, String request) {

        Connection conn = null;
        Statement stmt = null;

        try{

            try {
                conn = DatabasePools.getConnection();
            } catch (Exception e) {
                Class.forName("com.mysql.jdbc.Driver").newInstance();
                conn = DriverManager.getConnection("jdbc:mysql://10.10.152.228:3306/postgirl?",
                        "root",
                        "123456");
            }
            stmt = conn.createStatement();

            String sql = "select response as RESP from auto_collect_method_params where request_hash = '" + request + "'";
            ResultSet resultSet = stmt.executeQuery(sql);
            Map<String,String> map = new HashMap<String,String>();
            while(resultSet.next()) {
                String key = resultSet.getString("RESP");
                if (key != null) {
                    return key;
                }
            }

        } catch (Exception e) {
            System.out.print(e.getMessage());
            e.printStackTrace();
        } finally {
            try {
                stmt.close();
                conn.close();
            } catch (SQLException e) {
                System.out.print("Can't close stmt/conn because of " + e.getMessage());
            }
        }

        return null;
    }

}
